package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.vo.Node;
import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysMenu;
import com.cy.pj.sys.pojo.SysUserMenu;
import com.cy.pj.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author 张琪
 * @date 2020/11/14
 * @describe
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String, Object>> list = sysMenuDao.findObjects();
        if(list == null || list.size() == 0)
            throw new ServiceException("没有对应的菜单信息");
        return list;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        List<Node> list = sysMenuDao.findZtreeMenuNodes();
        if(list == null || list.size() == 0)
            throw new ServiceException("没有对应的菜单信息");
        return list;
    }

    @Override
    public int saveObject(SysMenu sysMenu) {
        if(sysMenu == null){
            throw new ServiceException("保存对象不能为空");
        }
        int rows = sysMenuDao.insertObject(sysMenu);
        return rows;
    }

    @Override
    public int deleteObject(Integer id) {
        int rowCount = sysMenuDao.getChildCount(id);
        if(rowCount > 0){
            throw new ServiceException("该节点还存在子节点, 不能删除");
        }
//        关联数据
        int row = sysRoleMenuDao.deleteObjectsByMenuId(id);

        return sysMenuDao.deleteObject(id);
    }

    @Override
    public int updateObject(SysMenu sysMenu) {
        if(sysMenu == null){
            throw new ServiceException("保存对象不能为空");
        }
        int rows = sysMenuDao.updateObject(sysMenu);
        return rows;
    }


    public List<SysUserMenu> findUserMenusByUserId(Integer id) {
//        1. 参数判断
//        2. userId-->roleIds-->menuIds
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(id);

        List<Integer> menuIds = sysRoleMenuDao.findMenuIdsByIds(roleIds);

        List<SysUserMenu> records = sysMenuDao.findMenusByIds(menuIds);

        return records;
    }
}
